Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Method

method in java

What is a Method in Java? A method in Java is a collection of statements that perform a specific task. It’s used to expose the behavior of an object. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class. Syntax of a Method The general syntax for declaring a method in Java is as follows:
Method structure class { (list_of_parameters) { // body } }
Components of a Method A method declaration in Java has six components: Modifier: It defines the access type of the method. Return Type: The data type of the value returned by the method or void if it does not return a value. Method Name: The rules for field names apply to method names as well, but the convention is a little different. Parameter List: Comma-separated list of the input parameters is defined, preceded by their data type, within the enclosed parenthesis. Exception List: The exceptions you expect by the method can throw, you can specify these exception(s). Method Body: It is enclosed between braces. The code you need to be executed to perform your intended operations. Types of Methods in Java There are two types of methods in Java: Predefined Method: These are the methods that are already defined in the Java class libraries. User-defined Method: The methods written by the user or programmer. Example of a Method in Java Here’s an example of a method in Java:
Java method basic example public int addNumbers(int a, int b) { int sum = a + b; return sum; }
In this example, addNumbers is a method that takes two parameters (a and b), adds them together, and returns the result.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops

Tutorials